

//
//  YYYHomePageCell.swift
//  HotNews
//
//  Created by YYY on 2017/10/19.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

/*
 cell的性能优化：
 1:尽量少计算，所需要的素材提前准备好。
 2:cell中的控件越少越好，层次越少越好。
 3:缓存行高是解决性能优化的最佳途径。
 4:尽量不要设置图片圆角，离屏渲染和栅格化要注意。
 5:不要动态的创建控件，所需要的控件都有事先创建好，在展示的时候根据需要显示或者隐藏。
 高级性能优化：
 1:离屏渲染  异步绘制
 2:栅格化 异步绘制之后。会生成一张独立的图像，cell在屏幕上滚动的时候，本质上是滚动这张图片。
 离屏渲染需要在CPU和GPU之间快读切换，并且耗电比较厉害。
 */
/*
 //测试4张图片
 var urls = viewModel?.homeModel.pic_urls ?? []
 if urls.count > 4
 {
 urls.removeSubrange(urls.startIndex + 4 ..< urls.endIndex)
 }
 pictureView.urls = urls
 */

import UIKit

//Swift定义代理
/*
 定义协议可选
1:用@objc protocol修饰协议
2:用@objc optional修饰方法
*/
@objc protocol YYYHomePageCellDelegate: NSObjectProtocol
{
    //定义方法可选
    @objc func homePageCellDidSelectedUrlString(urlString: String)
}
class YYYHomePageCell: UITableViewCell {
    //定义代理
    weak var delegate: YYYHomePageCellDelegate?
    
    //顶部视图
    private lazy var topView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: kDeviceWidth, height: 12))
    //头像
    private lazy var avatarImage = UIImageView(image: UIImage(named: "avatar_default_big"))
    //认证图标
    private lazy var vertifyImage = UIImageView(image: UIImage(named: "avatar_vip"))
    //姓名
    private lazy var nameLabel = UILabel(text: "", fontSize: 15, color: UIColor.hexStringColor(hexString: "#1452B8"))
    //会员
    private lazy var memberImage = UIImageView(image: UIImage(named: "common_icon_membership_level1"))
    //日期
    private lazy var dateLabel = UILabel(text: "", fontSize: 12, color: UIColor.hexStringColor(hexString: "#145296"))
    //来源
    private lazy var sourceLabel = UILabel(text: "", fontSize: 12, color: UIColor.hexStringColor(hexString: "#828282"))
    
    //被转发微博内容布局
    private lazy var retweetButton = UIButton(frame: CGRect(x: 0, y: 0, width: kDeviceWidth, height: 40))
    //被转发的标题
    private lazy var retweetLabel = YYYTextKitLabel(text: "", fontSize: 14, color: UIColor.darkGray)
    
    //配图视图
    private var pictureView = YYYHomePictureView(frame: CGRect(x: kPictureViewOutterMargin, y: 0, width: kDeviceWidth - 2 * kPictureViewOutterMargin, height: 0))
    
    //正文
    private lazy var contextLabel = YYYTextKitLabel(text: "", fontSize: 15, color: UIColor.darkGray)
    
    //底部工具栏
    private lazy var bottomView = YYYHomeToolBar(frame: CGRect(x: 0, y: 0, width: kDeviceWidth, height: 35))
    
    //设置控件数据
    var viewModel: YYYHomeViewModel?
    {
        didSet
        {
            //头像
            avatarImage.sd_setImageUrl(urlString: viewModel?.homeModel.user?.profile_image_url, placeholderString: "avatar_default_big", isAvatar: true)
            
            //认证图标
            vertifyImage.image = viewModel?.vertifyImage
            
            //姓名
            nameLabel.text = viewModel?.homeModel.user?.screen_name
            nameLabel.setWidth(newWidth: viewModel?.nameWidth ?? 0)
            
            //会员图标
            memberImage.image = viewModel?.memberImage
            memberImage.setLeft(newLeft: nameLabel.right+3)
            
            dateLabel.text = viewModel?.homeModel.createdDate?.dateDescriptionString
            if let text = dateLabel.text
            {
                let dateWidth = text.calculateLabelSize(fontSize: 12, size: CGSize(width: CGFloat(MAXFLOAT), height: 10)).width
                dateLabel.setWidth(newWidth: dateWidth)
            }
        
            //微博来源
            if let text = viewModel?.homeModel.source //viewModel?.sourceString
            {
                sourceLabel.text = text
                let sourceWidth = text.calculateLabelSize(fontSize: 12, size: CGSize(width: CGFloat(MAXFLOAT), height: 10)).width
                sourceLabel.setWidth(newWidth: sourceWidth)
            }
            sourceLabel.setLeft(newLeft: dateLabel.right + 6)
            
            //正文
            contextLabel.attributedText = viewModel?.contextAttributed
            
            contextLabel.setHeight(newHeight: viewModel?.contextHeight ?? 0)
            
            if viewModel?.homeModel.retweeted_status != nil
            {
                //被转发微博的配图视图
                retweetButton.isHidden = false
                retweetLabel.isHidden = false
                
                let retweetLabelHeight = viewModel?.retweetTextHeight ?? 0
                let pictureViewHeight = viewModel?.pictureSize.height ?? 0
                
                retweetButton.setTop(newTop: contextLabel.bottom+12)
                retweetButton.setHeight(newHeight: retweetLabelHeight + pictureViewHeight + 12)
                
                retweetLabel.setTop(newTop: retweetButton.top + 12)
                retweetLabel.setHeight(newHeight: retweetLabelHeight)
                retweetLabel.attributedText = viewModel?.retweetTextAttributed
                
                pictureView.setTop(newTop: retweetLabel.bottom)
            }
            else
            {
                //原创微博的配图视图
                retweetButton.isHidden = true
                retweetLabel.isHidden = true
                pictureView.setTop(newTop: contextLabel.bottom)
            }
            pictureView.viewModel = viewModel
            
            //底部工具栏
            bottomView.viewModel = viewModel
            let cellRowHeight = (viewModel?.rowHeight ?? 0) - 35
            bottomView.setTop(newTop: cellRowHeight)
        }
    }
    override init(style: UITableViewCellStyle, reuseIdentifier: String?)
    {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension YYYHomePageCell: YYYTextKitLabelDelegate
{
    //实现协议方法
    func textKitLabelDidSelectedLinkText(label: YYYTextKitLabel, text: String)
    {
        if !text.hasPrefix("http")
        {
            return
        }
        //让代理去实现协议方法
        delegate?.homePageCellDidSelectedUrlString(urlString: text)
    }
}
extension YYYHomePageCell
{
    //初始化子控件
    private func setupUI()
    {
//        //离屏渲染
//        layer.drawsAsynchronously = true
//        //栅格化
//        layer.shouldRasterize = true
//        //栅格化必须指定分辨率
//        layer.rasterizationScale = UIScreen.main.scale

        //添加子控件
        contentView.addSubview(topView)
        contentView.addSubview(avatarImage)
        contentView.addSubview(vertifyImage)
        contentView.addSubview(nameLabel)
        contentView.addSubview(memberImage)
        contentView.addSubview(dateLabel)
        contentView.addSubview(sourceLabel)
        contentView.addSubview(contextLabel)
        
        contentView.addSubview(bottomView)

        contentView.addSubview(retweetButton)
        contentView.addSubview(retweetLabel)
        contentView.addSubview(pictureView)
    
        //顶部视图
        topView.backgroundColor = UIColor.hexStringColor(hexString: "#f2f2f2")
        
        //头像
        avatarImage.frame = CGRect(x: 12, y: topView.bottom+12, width: 34, height: 34)
        //认证图标
        vertifyImage.center.x = avatarImage.right - 4
        vertifyImage.center.y = avatarImage.bottom - 4
        
        //姓名
        nameLabel.frame = CGRect(x: avatarImage.right+11, y: avatarImage.top, width: 100, height: 20)
      
        //会员
        memberImage.center.y = nameLabel.center.y
        
        //日期
        dateLabel.frame = CGRect(x: nameLabel.left, y: 0, width: 35, height: 10)
        dateLabel.setBottom(newBottom: avatarImage.bottom)
        
        //来源
        sourceLabel.frame = CGRect(x: dateLabel.right+6, y: 0, width: 120, height: 10)
        sourceLabel.center.y = dateLabel.center.y
        
        //正文
        contextLabel.numberOfLines = 0
        contextLabel.frame = CGRect(x: avatarImage.left, y: avatarImage.bottom+12, width: kDeviceWidth - 2 * avatarImage.left , height: 0)
        
        //被转发微博
        retweetButton.backgroundColor = UIColor.RGBColor(red: 244, green: 244, blue: 244)
        
        //被转发的文本内容
        retweetLabel.numberOfLines = 0
        retweetLabel.setLeft(newLeft: 12)
        retweetLabel.setWidth(newWidth: kDeviceWidth - 24)
        
        //设置代理
        contextLabel.delegate = self
        retweetLabel.delegate = self
    }
}
